package com.matace.keychain.data;

import android.content.Context;
import android.content.SharedPreferences;
import com.matace.keychain.domain.UserRepository;

/**
 * 用户仓库实现类
 * 实现了UserRepository接口，负责用户数据的存储和读取
 */
public class UserRepositoryImpl implements UserRepository {
    // SharedPreferences相关常量
    private static final String PREFS_NAME = "LoginPrefs";
    private static final String KEY_REMEMBER_ME = "rememberMe";
    private static final String KEY_USERNAME = "username";
    private static final String KEY_PASSWORD = "password";

    private final SharedPreferences prefs;
    private final Context context;

    /**
     * 构造函数
     * @param context 应用上下文
     */
    public UserRepositoryImpl(Context context) {
        this.prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        this.context = context;
    }

    /**
     * 通过邮箱登录
     * 首先尝试从数据库验证，如果失败则使用默认账号
     */
    @Override
    public boolean loginByEmail(String username, String password) {
        DatabaseManager databaseManager = new DatabaseManager(context);

        if (databaseManager.isLoginEmail(username, password)) {
            return true;
        }
        
        return "angelo".equals(username) && "123456".equals(password);
    }

    /**
     * 通过用户名登录
     * 首先尝试从数据库验证，如果失败则使用默认账号
     */
    @Override
    public boolean loginByName(String username, String password) {
        DatabaseManager databaseManager = new DatabaseManager(context);

        if (databaseManager.isLoginUser(username, password)) {
            return true;
        }

        return "angelo".equals(username) && "123456".equals(password);
    }

    /**
     * 获取保存的用户名
     */
    @Override
    public String getSavedUsername() {
        return prefs.getString(KEY_USERNAME, "");
    }

    /**
     * 获取保存的密码
     */
    @Override
    public String getSavedPassword() {
        return prefs.getString(KEY_PASSWORD, "");
    }

    /**
     * 检查是否记住登录状态
     */
    @Override
    public boolean isRememberMe() {
        return prefs.getBoolean(KEY_REMEMBER_ME, false);
    }

    /**
     * 保存用户登录凭证
     * 同时设置记住登录状态为true
     */
    @Override
    public void saveCredentials(String username, String password) {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(KEY_REMEMBER_ME, true);
        editor.putString(KEY_USERNAME, username);
        editor.putString(KEY_PASSWORD, password);
        editor.apply();
    }

    /**
     * 清除保存的登录凭证
     * 同时设置记住登录状态为false
     */
    @Override
    public void clearCredentials() {
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(KEY_REMEMBER_ME, false);
        editor.remove(KEY_USERNAME);
        editor.remove(KEY_PASSWORD);
        editor.apply();
    }
}